<template>
  <div class="logs-container">
    <!-- Header -->
    <el-card class="mb16" shadow="hover">
      <div class="logs-header">
        <h1 class="page-title">系统日志</h1>
        <p class="page-subtitle">查看系统操作日志和错误记录</p>
      </div>
    </el-card>

    <!-- Filters -->
    <el-card class="mb16" shadow="hover">
      <el-form :model="filters" label-width="90px" class="filters-form" @submit.prevent>
        <el-row :gutter="12">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="日志级别">
              <el-select v-model="filters.level" placeholder="选择级别" clearable>
                <el-option label="全部" value="" />
                <el-option label="信息" value="info" />
                <el-option label="警告" value="warn" />
                <el-option label="错误" value="error" />
                <el-option label="调试" value="debug" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="模块">
              <el-select v-model="filters.module" placeholder="选择模块" clearable>
                <el-option label="全部" value="" />
                <el-option label="认证模块" value="auth" />
                <el-option label="用户模块" value="user" />
                <el-option label="商品模块" value="product" />
                <el-option label="订单模块" value="order" />
                <el-option label="系统模块" value="system" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                unlink-panels
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :xs="24" :sm="16" :md="18">
            <el-form-item label="关键词">
              <el-input v-model="filters.keyword" placeholder="搜索日志内容..." clearable @keyup.enter="searchLogs" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6" class="toolbar">
            <el-button type="primary" @click="searchLogs">
              <el-icon><Search /></el-icon>
              <span class="ml6">搜索</span>
            </el-button>
            <el-button @click="resetFilters">
              <el-icon><Refresh /></el-icon>
              <span class="ml6">重置</span>
            </el-button>
            <el-button type="success" plain @click="exportLogs">
              <el-icon><Download /></el-icon>
              <span class="ml6">导出</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- Table -->
    <el-card class="mb16" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>日志记录</span>
          <div class="header-actions">
            <span class="text-muted">共 {{ totalLogs }} 条记录</span>
            <el-button link @click="refreshLogs">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="pagedLogs" border stripe highlight-current-row @row-click="showLogDetail" style="width: 100%">
        <el-table-column prop="createdAt" label="时间" min-width="160">
          <template #default="{ row }">
            <small class="text-muted">{{ formatDate(row.createdAt) }}</small>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" effect="light">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" min-width="120">
          <template #default="{ row }">
            <el-tag type="info" effect="plain">{{ row.module }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户" min-width="120">
          <template #default="{ row }">
            {{ row.username || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作" min-width="140" />
        <el-table-column prop="message" label="详情" min-width="260" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" min-width="140">
          <template #default="{ row }">
            <small class="text-muted">{{ row.ipAddress }}</small>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrap">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="totalLogs"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          @current-change="changePage"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- Detail Dialog -->
    <el-dialog v-model="showDetailModal" title="日志详情" width="700px" :close-on-click-modal="false">
      <div v-if="selectedLog">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="时间">{{ formatDate(selectedLog.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLevelTagType(selectedLog.level)">{{ getLevelText(selectedLog.level) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块">{{ selectedLog.module }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ selectedLog.username || "-" }}</el-descriptions-item>
          <el-descriptions-item label="操作">{{ selectedLog.action }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedLog.ipAddress }}</el-descriptions-item>
          <el-descriptions-item label="用户代理">
            <small class="text-muted">{{ selectedLog.userAgent }}</small>
          </el-descriptions-item>
        </el-descriptions>

        <div class="mt12">
          <strong>消息</strong>
          <el-card class="mt8" shadow="never">
            {{ selectedLog.message }}
          </el-card>
        </div>

        <div v-if="selectedLog.details" class="mt12">
          <strong>详细信息</strong>
          <el-card class="mt8" shadow="never">
            <pre class="mb0">{{ formatDetails(selectedLog.details) }}</pre>
          </el-card>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetailModal = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { Download, Refresh, Search } from "@element-plus/icons-vue";

defineOptions({ name: "LogsView" });

// 响应式数据
const showDetailModal = ref(false);
const selectedLog = ref<any>(null);
const currentPage = ref(1);
const pageSize = ref(20);
const totalLogs = ref(0);
const dateRange = ref<[string, string] | null>(null);

const filters = reactive({
  level: "",
  startDate: "",
  module: "",
  endDate: "",
  keyword: "",
});

// 模拟日志数据生成器
type LogItem = {
  id: number;
  level: "info" | "warn" | "error" | "debug";
  module: "auth" | "user" | "product" | "order" | "system";
  username: string | null;
  action: string;
  message: string;
  ipAddress: string;
  userAgent: string;
  createdAt: string; // ISO string
  details?: any;
};

function pad(n: number) {
  return n.toString().padStart(2, "0");
}
function makeDate(year: number, month: number, day: number, hour: number, min: number): string {
  const d = new Date(Date.UTC(year, month - 1, day, hour, min, 0));
  return d.toISOString();
}
function generateMockLogs(count = 200): LogItem[] {
  const levels = ["info", "warn", "error", "debug"] as const;
  const modules = ["auth", "user", "product", "order", "system"] as const;
  const actions = ["用户登录", "修改用户信息", "创建商品", "创建订单", "系统检查"];
  const messages = [
    "用户 admin 成功登录系统",
    "尝试修改不存在的用户信息",
    "创建商品失败：数据库连接超时",
    "用户 user2 成功创建订单",
    "定时任务执行：清理过期会话",
    "API调用返回慢，触发预警",
    "权限校验失败，拒绝访问",
    "库存同步完成",
    "支付回调处理成功",
  ];
  const users = ["admin", "user1", "user2", "auditor", "ops", null];
  const agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/537.36",
    "System/1.0",
    "curl/8.0.1",
  ];
  const ip = (i: number) => `192.168.1.${100 + (i % 50)}`;
  const logs: LogItem[] = [];
  const baseYear = 2024;
  for (let i = 1; i <= count; i++) {
    const lv = levels[i % levels.length];
    const md = modules[i % modules.length];
    const user = users[i % users.length];
    const act = actions[i % actions.length];
    const msg = messages[i % messages.length];
    const agent = agents[i % agents.length];
    const day = 1 + (i % 28);
    const hour = i % 24;
    const min = i % 60;
    logs.push({
      id: i,
      level: lv,
      module: md,
      username: user as string | null,
      action: act,
      message: msg,
      ipAddress: ip(i),
      userAgent: agent,
      createdAt: makeDate(baseYear, 1 + (i % 12), day, hour, min),
      details: { index: i, note: "mock-generated" },
    });
  }
  return logs;
}

const logs = ref<LogItem[]>(generateMockLogs(200));

// 计算属性：总页数与过滤后数据
const totalPages = computed(() => Math.ceil(totalLogs.value / pageSize.value));

function matchLevel(l: LogItem, level: string) {
  return !level || l.level === level;
}
function matchModule(l: LogItem, module: string) {
  return !module || l.module === module;
}
function matchDateRange(l: LogItem, start: string, end: string) {
  if (!start && !end) return true;
  const d = new Date(l.createdAt);
  if (start) {
    const ds = new Date(start + "T00:00:00");
    if (d < ds) return false;
  }
  if (end) {
    const de = new Date(end + "T23:59:59");
    if (d > de) return false;
  }
  return true;
}
function matchKeyword(l: LogItem, keyword: string) {
  const kw = (keyword || "").trim().toLowerCase();
  if (!kw) return true;
  const text = [l.message, l.action, l.module, l.username ?? "", l.ipAddress, l.userAgent].join(" ").toLowerCase();
  return text.includes(kw);
}

const filteredLogs = computed(() =>
  logs.value.filter(
    (l) =>
      matchLevel(l, filters.level) &&
      matchModule(l, filters.module) &&
      matchDateRange(l, filters.startDate, filters.endDate) &&
      matchKeyword(l, filters.keyword),
  ),
);

const pagedLogs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredLogs.value.slice(start, start + pageSize.value);
});

// 事件与方法
const formatDate = (dateString: string) => new Date(dateString).toLocaleString("zh-CN");
const formatDetails = (obj: unknown) => JSON.stringify(obj, null, 2);

const getLevelText = (level: string) => {
  const levelMap: Record<string, string> = { info: "信息", warn: "警告", error: "错误", debug: "调试" };
  return levelMap[level] || level;
};
const getLevelTagType = (level: string): "success" | "warning" | "danger" | "info" => {
  switch (level) {
    case "info":
      return "info";
    case "warn":
      return "warning";
    case "error":
      return "danger";
    case "debug":
      return "success";
    default:
      return "info";
  }
};

const showLogDetail = (log: LogItem) => {
  selectedLog.value = log;
  showDetailModal.value = true;
};

const searchLogs = () => {
  // 将日期范围映射到 startDate/endDate
  filters.startDate = dateRange.value?.[0] || "";
  filters.endDate = dateRange.value?.[1] || "";
  currentPage.value = 1;
  totalLogs.value = filteredLogs.value.length;
  console.log("搜索日志:", { ...filters, total: totalLogs.value });
};

const resetFilters = () => {
  Object.assign(filters, { level: "", module: "", startDate: "", endDate: "", keyword: "" });
  dateRange.value = null;
  searchLogs();
};

const exportLogs = () => {
  console.log("导出日志");
};

const refreshLogs = () => {
  console.log("刷新日志");
};

const changePage = (page: number) => {
  currentPage.value = page;
};
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

onMounted(() => {
  totalLogs.value = filteredLogs.value.length;
  console.log("系统日志页面加载完成，数据量:", logs.value.length);
});

watch([logs, () => filters.level, () => filters.module, () => filters.keyword, dateRange], () => {
  // 保持 total 同步
  totalLogs.value = filteredLogs.value.length;
});
</script>

<style scoped>
.logs-container {
  padding: 16px;
  background: var(--el-bg-color-page);
  min-height: 100vh;
}
.logs-header .page-title {
  color: #5a5c69;
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}
.logs-header .page-subtitle {
  color: #858796;
  margin: 8px 0 0;
}
.mb16 {
  margin-bottom: 16px;
}
.ml6 {
  margin-left: 6px;
}
.mt8 {
  margin-top: 8px;
}
.mt12 {
  margin-top: 12px;
}
.mb0 {
  margin-bottom: 0;
}
.toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
.text-muted {
  color: var(--el-text-color-secondary);
}
.pagination-wrap {
  display: flex;
  justify-content: center;
  padding: 12px 0 0;
}
pre {
  font-size: 12px;
  max-height: 240px;
  overflow-y: auto;
}
</style>
